<template>
	<view class="main-container">
		<view class="interface">
			<text class="corner-text top-left" style="font-size: 35rpx;">设备</text>
			<text class="corner-text top-right" v-if="!connectionStatus" @click="initBlue">搜索设备并连接</text>
			<text class="corner-text top-right" v-else @click="disConnectd">点击断开连接</text>
			<!-- <image src="../../static/images/blood_oxygen.png"></image> -->
			<text class="corner-text bottom-left">体温测温仪\n <text style="color:#808080 ;">A0J-30B</text></text>
			<text class="corner-text bottom-right" style="font-size: 50rpx;font-weight: bolder;">
				·<text style="color: black;font-size: 30rpx;font-weight: normal;" v-if="!connectionStatus">
					未连接</text>
	<!-- 			<text v-else style="color: black;font-size: 30rpx;font-weight: normal;" @click="getCharacteristics">
					已连接,点击开始测量</text> -->
					<text v-else style="color: black;font-size: 30rpx;font-weight: normal;" @click="mockTest()">
						已连接,点击开始测量</text>
			</text>
		</view>
		<uni-popup ref="popup" :mask-click="true" @close="handlePopupClose">
			<device-connection :device-name="deviceName" @send="connetionCallBack"  ref="deviceConnection">
			</device-connection>
		</uni-popup>
		<view style="margin-top: 60%;">
			<text>后面的值都在这里</text>
			<text>体温值为:{{tempretureValue[tempretureValue.length - 1]}}</text>
			<tempreture-card style="margin-top: 70%;" :array="tempresureList"></tempreture-card>
		</view>
	</view>
</template>
<script>
	import {postTempresureInfo,getTempresureInfo} from '../../api/tempresure'
	export default {
		created() {
			this.tempretureInfo.userId = this.$store.state.user.currId
			console.log(this.$store.state.user)
			getTempresureInfo(this.$store.state.user.currId).then(res => {
				console.log(res)
				this.tempresureList = res
			})
			console.log(this.tempresureList)
		},
		data() {
			return {
				tempretureInfo: {
					"tempretureValue": "",
					"userId": 0
				},
				tempresureList:[],
				deviceName:"测温仪器",
				tempretureValue:[],
				connectionStatus: true,
				bluetoothDevices: [], // 存储蓝牙设备列表
				serviceId: "",
				notifyId: "",
				deviceId: "" ,// 0xFFE0，0xFFE1 0xFFE2
				valueList:[] // 这里的话要对第三个数除10
			}
		},
		methods: {
			mockTest() {
			  let value = 36.2;
			  let i = 0;
			  const delayedLoop = () => {
			    if (i < 5) {
			      setTimeout(() => {
			        console.log(i);
			        if (i <= 5) {
			          value += 0.1;
			          this.valueList.push(value);
			        } else {
			          value -= 0.1;
			          this.valueList.push(value);
			        }
			        i++;
			        delayedLoop(); // 递归调用 delayedLoop 函数
			      }, 1000); // 每次迭代延迟 3000 毫秒执行
			    } else {
			      console.log("test over");
						this.tempretureInfo.tempretureValue = value.toFixed(2)
						this.tempretureValue.push(value.toFixed(2))
						this.postTempresure()
			    }
			  };
			  delayedLoop(); // 启动递归函数
			},
			postTempresure() {
				postTempresureInfo(this.tempretureInfo).then(res => {
					console.log(res)
					getTempresureInfo(this.$store.state.user.currId).then(res => {
						console.log(res)
						this.tempresureList = res
					})
				}).catch(err => {
					console.log(err)
				})
			},
			connetionCallBack(deviceId,serviceId) {
			  this.deviceId = deviceId
				this.serviceId = serviceId
				console.log('Received deviceId:', deviceId);
				console.log('Received serviceUuid:', serviceId);
				this.connectionStatus = true
			},
			handlePopupClose() {
				this.$refs.popup.close();
				this.stopBluetoothDiscovery();
			},
			disConnectd() {
				this.connectionStatus = false;
				this.postTempresure()
				this.closeConnection()
			},
			initBlue() {
				uni.openBluetoothAdapter({
					success: (res) => {
						console.log("初始化蓝牙成功");
						console.log(res);
						this.$refs.popup.open('center');
						this.$refs.deviceConnection.init();
					},
					fail: (err) => {
						console.log("初始化蓝牙失败");
						console.error(err);
					},
				});
			},
			stopBluetoothDiscovery() {
			  uni.stopBluetoothDevicesDiscovery({
			    success: (res) => {
			      console.log("蓝牙搜索已停止", res);
			      // this.bluetoothDevices = [];
			    },
			    fail: (err) => {
			      console.error("停止蓝牙搜索失败", err);
			    },
			  });
			},
			notifyDevice(notifyId) {
			  console.log("进入了消息监听，下面是特征值");
			  console.log(notifyId);
			  console.log("正在进行监听数据");
			  uni.notifyBLECharacteristicValueChange({
			    state: true,
			    deviceId: this.deviceId, // 设备ID，在【4】里获取到
			    serviceId: this.serviceId, // 服务UUID，在【6】里能获取到
			    characteristicId: notifyId, // 特征值，在【7】里能获取到
			    success:(res) =>{
						console.log("监听成功")
			      console.log(res);
			      // 接受消息的方法
			      this.listenValueChange();
			    },
			    fail :(err)=> {
						console.log("监听失败，原因如下")
			      console.error(err);
			    },
			  });
			},
			getCharacteristics() {
			  uni.getBLEDeviceCharacteristics({
			    deviceId: this.deviceId, // 设备ID，在【4】里获取到
			    serviceId: this.serviceId, // 服务UUID，在【6】里能获取到
			    success: (res) => {
			      this.characteristicIdList = res.characteristics;
			      for (let i = 0; i < this.characteristicIdList.length; i++) {
			        // console.log(this.characteristicIdList[i])
			        if (this.characteristicIdList[i].properties.notify) {
			          this.characteristicId = this.characteristicIdList[i].uuid;
			          this.notifyId = this.characteristicIdList[i].uuid;
			          console.log(this.notifyId);
			          this.notifyDevice(this.notifyId);
			          console.log("获取特征值成功且赋值成功");
			          break;
			        }
			      }
			    },
			    fail: (err)=> {
			      console.error("获取特征值失败");
			      console.error(err);
			    },
			  });
			},
			getTime() {
				// 创建一个新的日期对象
				var now = new Date();
				
				// 获取年份
				var year = now.getFullYear();
				
				// 获取月份（0-11）
				var month = now.getMonth() + 1;
				
				// 获取日期
				var date = now.getDate();
				
				// 获取小时
				var hours = now.getHours();
				
				// 获取分钟
				var minutes = now.getMinutes();
				
				// 获取秒钟
				var seconds = now.getSeconds();
				
				// 格式化输出时间
				var formattedTime = year + '-' + month + '-' + date + ' ' + hours + ':' + minutes + ':' + seconds;
				
				// 在控制台打印时间
				console.log(formattedTime);
			
			},
			listenValueChange() {
				console.log("监听中...")
				this.getTime()
				uni.onBLECharacteristicValueChange((res) => {
					// 结果里有个value值，该值为 ArrayBuffer 类型，所以在控制台无法用肉眼观察到，必须将该值转换为16进制
					 let resHex = this.ab2hex(res.value);
					 // console.log(resHex);
					 this.check(resHex);
				});
			},
			check(str){
			    if(str.substring(0,6) == "aa01c1"){
			        console.log("测量成功")
							this.valueList = this.hexToDecimal(str);
							this.tempretureValue.push(this.valueList[4])
			        console.log(this.valueList)
							this.tempretureInfo.tempretureValue = this.valueList[4]
			    }else {
						console.log("未知数据")
						console.log(this.hexToDecimal(str))
					}
			},
			closeConnection() {
				console.log("正在断开连接")
				this.getTime()
				uni.closeBLEConnection({
				  deviceId : this.deviceId,
				  success: (res)=>{
				    console.log(res)
						console.log("断开连接成功")
				  },
					fail: (err) => {
						console.log(err)
						console.log("断开连接失败")
					}
				})
			},
			ab2hex(buffer) {
			  const hexArr = Array.prototype.map.call(
			    new Uint8Array(buffer),
			    function (bit) {
			      return ("00" + bit.toString(16)).slice(-2);
			    }
			  );
			  return hexArr.join("");
			},
			hexToDecimal(hexString) {
				var dataList = [];
				dataList.push(parseInt(hexString.substring(0, 2), 16)); // 数据起始位
				dataList.push(parseInt(hexString.substring(2, 4), 16)); // 设备名
				dataList.push(parseInt(hexString.substring(4, 6), 16)); // 数据命令位
				dataList.push(parseInt(hexString.substring(6, 8), 16)); // 测量次数
				// 测温数据
				var temperature = parseInt(hexString.substring(8, 12), 16) / 100.0;
				temperature = Math.round(temperature * 10) / 10;
				dataList.push(temperature);
				dataList.push(parseInt(hexString.substring(12, 14), 16)); // 测温模式
				// 异或校验位
				var xorValue = dataList[1] ^ dataList[2] ^ dataList[3] ^ parseInt(temperature * 10) ^ dataList[5];
				dataList.push(xorValue);
				return dataList;
			}
		}
	}
</script>

<style>
	.interface{
	  /* position: absolute; */
	  flex-wrap:wrap;
		position: absolute;
	  width: 85%;
	  height: 25%;
	  left: 7%;
	  top:28%;
	  background: #FFFFFF;
	  box-shadow: 4px 4px 4px #94D6E2;
	  border-radius: 15px;

  }

  .corner-text {
    font-size: 12px;
    position: absolute;
	
  }
  
  .top-left {
    top: 10px;
    left: 10px;
  }
  
  .top-right {
    top: 10px;
    right: 10px;
    color: #48C454; /* 绿色文本 */
  }
  
  .bottom-left {
    bottom: 10px;
    left: 10px;
  }
  
  .bottom-right {
    bottom: 10px;
    right: 10px;
    color: #48C454; /* 绿色文本 */
  }
  

  .data-card {
  display: flex; 
  justify-content: center;
  align-items: center;
  flex-direction: column;
  width: 100%;
  background-color: #FFFFFF;
  margin-top: 50%;
  }

 .pressure{
    display: flex;
	justify-content:center;
	width: 100%;
	flex-direction: row;
 /*   align-items: center; */
  }
  
  .vvv{
	  display: flex;
	  flex-direction: column;
	  align-items: center;
	  margin-top: 20rpx;
	  margin-bottom: 20rpx;
	  margin-right: 40rpx;
	  margin-left: 40rpx;
  }
  
  .vertical-line {
    height: 80rpx; /* 控制竖线的高度 */
    width: 2px; /* 控制竖线的宽度 */
    background-color: #CCCCCC;
    margin: 0 20rpx; 
  }
  .label {
    font-size: 12px;
    color: #808080; /* 灰色文本 */
  }
</style>